package com.zhenyi.api.file;

import java.io.File;

import com.cenjiawen.common.IndexController;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import com.qiniu.common.QiniuException;
import com.utils.image.UploadUtils;

import cn.hutool.core.io.FileUtil;

public abstract class QNController extends IndexController {

	protected abstract String getAK();

	protected abstract String getSK();

	/**
	 * 
	 * @return http://res.zhen-yee.com
	 * @Time 2019年1月14日 下午10:49:11
	 */
	protected abstract String getHost();

	protected abstract String getBucket();

	protected abstract String getProject();

	private QNUtils qnUtils = new QNUtils(getHost(), getBucket(), getAK(), getSK());

	/**
	 * 上传图片接口
	 */
	public void image() {
		try {
			File file = getFileParam("file");
			String url = UploadUtils.upload(file);
			renderSuccess(url);
		} catch (Exception e) {
			LogKit.warn("upload image fail ", e);
			renderFailure("upload image fai");
		}
	}

	public void token() {
		renderSuccess(qnUtils.getToken());
	}

	public void delete() {
		String key = getPara("key");
		if (StrKit.isBlank(key)) {
			renderError(404);
			return;
		}
		boolean flag = qnUtils.remove(key);
		renderFlag(flag);
	}

	public void upload() {
		File file = getFileParam("file");
		if (!file.exists()) {
			renderFailure("no file");
			return;
		}
		String key = getPara("key");
		if (StrKit.isBlank(key)) {
			key = FileUtil.getName(file);
		}
		try {
			String url = qnUtils.uploadWithPrefix(file, getProject(), key);
			if (StrKit.isBlank(url)) {
				renderFailure("upload fail");
				return;
			}
			renderSuccess(url);
		} catch (QiniuException e) {
			LogKit.warn("upload qn file fail ", e);
			renderFailure("upload exception");
		}
	}
}
